package com.ktwlsoft.fundmanage.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * 雪花算法id生成工具类
 *
 * @author zhuhe on 2019/2/21 002117:31
 * @version 1.0
 */
public class KeyWorkerUtil {

    /** 日志对象 **/
    private static Logger logger = LoggerFactory.getLogger(KeyWorkerUtil.class);

    private final static long TWEPOCH = 12888349746579L;
    /** 机器标识位数*/
    private final static long WORKERIDBITS = 5L;
    /**数据中心标识位数*/
    private final static long DATACENTERIDBITS = 5L;
    /**毫秒内自增位数*/
    private final static long SEQUENCEBITS = 12L;
    /**机器ID偏左移12位*/
    private final static long WORKERIDSHIFT = SEQUENCEBITS;
    /**数据中心ID左移17位*/
    private final static long DATACENTERIDSHIFT = SEQUENCEBITS + WORKERIDBITS;
    /**时间毫秒左移22位*/
    private final static long TIMESTAMPLEFTSHIFT = SEQUENCEBITS + WORKERIDBITS + DATACENTERIDBITS;
    /**sequence掩码，确保sequnce不会超出上限*/
    private final static long SEQUENCEMASK = -1L ^ (-1L << SEQUENCEBITS);
    /**上次时间戳*/
    private static long LASTTIMESTAMP = -1L;
    /**序列*/
    private long sequence = 0L;
    /**服务器ID*/
    private long workerId = 1L;
    private static long WORKERMASK= -1L ^ (-1L << WORKERIDBITS);
    /**进程编码*/
    private long processId = 1L;
    private static long PROCESSMASK=-1L ^ (-1L << DATACENTERIDBITS);
    private static KeyWorkerUtil keyWorker = null;

    static{
        keyWorker=new KeyWorkerUtil();
    }

    private KeyWorkerUtil() {
        //获取机器编码
        this.workerId=this.getMachineNum();
        //获取进程编码
        RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
        this.processId=Long.parseLong(runtimeMXBean.getName().split("@")[0]);
        //避免编码超出最大值
        this.workerId=workerId & WORKERMASK;
        this.processId=processId & PROCESSMASK;
    }

    /**
     * 获取新的id on 2019/2/21 0021 17:46
     * @return long
     */
    public static synchronized long nextId(){
        return keyWorker.getNextId();
    }

    /**
     * 生成新id on 2019/2/21 0021 17:47
     * @return long
     */
    private synchronized long getNextId() {
        //获取时间戳
        long timestamp = timeGen();
        //如果时间戳小于上次时间戳则报错
        if (timestamp < LASTTIMESTAMP) {
            try {
                throw new Exception("Clock moved backwards.  Refusing to generate id for " + (LASTTIMESTAMP - timestamp) + " milliseconds");
            } catch (Exception e) {
                logger.error(e.getMessage());
            }
        }
        //如果时间戳与上次时间戳相同
        if (LASTTIMESTAMP == timestamp) {
            // 当前毫秒内，则+1，与SEQUENCEMASK确保sequence不会超出上限
            sequence = (sequence + 1) & SEQUENCEMASK;
            if (sequence == 0) {
                // 当前毫秒内计数满了，则等待下一秒
                timestamp = tilNextMillis(LASTTIMESTAMP);
            }
        } else {
            sequence = 0;
        }
        LASTTIMESTAMP = timestamp;
        // ID偏移组合生成最终的ID，并返回ID
        return ((timestamp - TWEPOCH) << TIMESTAMPLEFTSHIFT) | (processId << DATACENTERIDSHIFT) | (workerId << WORKERIDSHIFT) | sequence;
    }

    /**
     * 再次获取时间戳直到获取的时间戳与现有的不同
     * @param lastTimeStamp
     * @return long
     */
    private long tilNextMillis(final long lastTimeStamp) {
        long timestamp = this.timeGen();
        while (timestamp <= lastTimeStamp) {
            timestamp = this.timeGen();
        }
        return timestamp;
    }

    /**
     * 返回一个时间戳 on 2019/2/21 0021 17:48
     * @return long
     */
    private long timeGen() {
        return System.currentTimeMillis();
    }

    /**
     * 获取机器编码
     * @return long
     */
    private long getMachineNum(){
        long machinePiece;
        StringBuilder sb = new StringBuilder();
        Enumeration<NetworkInterface> e = null;
        try {
            e = NetworkInterface.getNetworkInterfaces();
        } catch (SocketException e1) {
            logger.error(e1.getMessage());
        }
        if(e != null) {
            while (e.hasMoreElements()) {
                NetworkInterface ni = e.nextElement();
                sb.append(ni.toString());
            }
        }
        machinePiece = sb.toString().hashCode();
        return machinePiece;
    }
}
